<template>
	<view class="">
		<view class="p-1 pb-0">
			<!-- 主播 -->
			<view class="flex" v-if="room.role==='anchor'">
				<view class="flex-1">
					<AnchorVue :params="params" :pause="pause" algin="row" @startLocalAudio="startLocalAudio">
					</AnchorVue>
				</view>
				<!--  -->
				<view class="flex-col items-center" style="width:144rpx">
					<nv-image src="/static/icons/connecting.png" width="48rpx" height="48rpx"></nv-image>
					<view class="" style="margin: 10rpx 0rpx;">
						<text class="color-white">{{userOption.userId?'正在连麦':'等待连麦'}}</text>
					</view>
					<text class="color-gray font-sm">{{timeFormat(time)}}</text>
				</view>
				<!--  -->
				<view class="flex-1 flex justify-center items-center">
					<UserVue :params="userOption" :anonymous="anonymous" :pause="pause" algin="row" :role="room.role"
						v-if="userOption.userId">
					</UserVue>
					<!-- <view v-else class="rounded-full" style="background:#C0C0C0;padding:20rpx">
					<nv-image src="/static/live/microphone.png" width="40rpx" height="40rpx"></nv-image>
				</view> -->
				</view>
			</view>
			<!-- 用户 -->
			<view class="flex" v-if="room.role==='user'">
				<view class="flex-1">
					<UserVue :params="userOption" :pause="pause" :anonymous="true" :role="room.role" algin="row-reverse"
						v-if="userOption.userId"></UserVue>
				</view>
				<!--  -->
				<view class="flex-col items-center" style="width:144rpx">
					<nv-image src="/static/icons/connecting.png" width="48rpx" height="48rpx"></nv-image>
					<view class="" style="margin: 10rpx 0rpx;">
						<text class="color-white">{{params.userId?'正在连麦':'等待连麦'}}</text>
					</view>
					<text class="color-gray font-sm">{{timeFormat(time)}}</text>
				</view>
				<!--  -->
				<view class="flex-1 flex justify-center items-center">
					<view class="flex-1" v-if="connectingUserId">
						<AnchorVue :params="params" :pause="pause" v-if="params.userId==user.id" algin="row-reverse"
							role='user' @startLocalAudio="startLocalAudio" @memberVoiAnchorEnd="memberVoiAnchorEnd">
						</AnchorVue>
						<UserVue :params="params" :anonymous="anonymous" :pause="pause" :role="room.role" algin="row"
							v-else></UserVue>
					</view>
					<view class="flex-h-center" v-else @click="openConnection">
						<view class="rounded-full " style="background:#C0C0C0;padding:20rpx">
							<nv-image src="/static/live/microphone.png" width="40rpx" height="40rpx"></nv-image>
						</view>
						<text class="color-white font-sm">连麦解惑</text>
					</view>
				</view>
			</view>
			<!--  -->
			<view class="">
				<!-- 排队列表 -->
				<uni-popup ref="popupRef" type="bottom" background-color="#fff" borderRadius="10px 10px 0px 0px">
					<view class="flex-col" style="height: 600rpx;">
						<scroll-view scroll-y="true" class="flex-1" v-if="queueList.length>0">
							<view class="p-2">
								<view class="flex items-center justify-between py-1" v-for="e,i in queueList" :key="i">
									<view class="flex">
										<text class="mr-1">{{i+1}}</text>
										<text>{{e.member.nickname}}</text>
										<text
											style="margin-left: 20rpx;">{{e.sts!==0?e.sts!==1?'连麦结束':'接麦中':'正在等待'}}</text>
									</view>
									<view class="flex" v-if="room.role=='anchor'">
										<button size="mini" v-if="e.sts==0" @click="userConnection(e)">上麦</button>
										<button size="mini" @click="delConnection(e)">{{e.sts==0?'删除':'结束'}}</button>
									</view>
									<view class="flex" v-if="room.role=='user'">
										<button size="mini" @click="delConnection(e)"
											v-if="e.sts==0&&e.member.id==user.id">取消</button>
									</view>
								</view>
							</view>
						</scroll-view>
						<view class="flex-center flex-1" v-else>
							<text>暂无数据</text>
						</view>
					</view>

				</uni-popup>
			</view>
		</view>
		<!-- 暂停 -->
		<view class="flex-center" style="height: 50rpx;"
			v-if="(room.role==='anchor'&&userOption.userId)||(room.role==='user'&&params.userId)">
			<view @click="onPause">
				<nv-image v-if="pause" src="/static/icons/pause.png" width="52rpx" height="50rpx"></nv-image>
				<nv-image v-else src="/static/icons/pause_.png" width="52rpx" height="50rpx"></nv-image>
			</view>
		</view>
	</view>
</template>

<script setup>
	import liveApi from '@/apis/apiList/liveApi';
	import TrtcCloud from '@/TrtcCloud/lib/index';
	import AnchorVue from './Anchor.vue';
	import UserVue from './User.vue';
	import nvImage from '@/uni_modules/uv-image/components/uv-image/uv-image.vue'
	import {
		TRTCAppScene,
		TRTCRoleType,
		TRTCVideoStreamType
	} from '@/TrtcCloud/lib/TrtcDefines';
	import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
	import TrtcRemoteView from '@/TrtcCloud/view/TrtcRemoteView';
	import {
		nextTick,
		ref,
	} from 'vue';
	import userApi from '@/apis/apiList/userApi';
	import dayjs from 'dayjs';
	let trtcCloud = TrtcCloud.createInstance(); //创建实例
	const videoRef = ref(null)
	const popupRef = ref(null)

	const room = ref({}) //直播间信息
	const pause = ref(true) //暂停
	const emit = defineEmits(['createCustomMessage', 'sendMsg', 'openConnection'])
	const user = uni.getStorageSync('user') //当前用户信息
	const liveOption = ref({}) //连接直播间必要参数
	const queueList = ref([]) //排序列表
	const connectingId = ref('') //麦序Id
	const connectingUserId = ref('') //连线用户Id
	const time = ref(0) //计时器
	const timeFormat = e => {
		return e ? dayjs().startOf('day').add(e, 'second').format('HH:mm:ss') : '00:00:00'
	}
	const params = ref({
		userId: "",
		headimg: '',
		nickname: '',
		live: false,
		audio: false
	})
	const userOption = ref({
		userId: "",
		headimg: '',
		nickname: '',
		live: false,
		audio: false
	})
	//初始化直播间
	const startLive = (val, options) => {
		room.value = val
		liveOption.value = options
		nextTick(() => {
			if (val.role == 'anchor') {
				// 主播
				params.value = {
					userId: options.userId,
					headimg: val.anchor.headimg,
					nickname: val.anchor.name,
					live: true,
					audio: true
				}

			}
			if (val.role == 'user') {
				userOption.value = {
					userId: val.anchor.member.id,
					headimg: val.anchor.headimg,
					nickname: val.anchor.name,
					live: true,
					audio: true
				}
			}
			// 进入房间
			enterRoom(true)
			// 监听
			onMonitor()
			// 排麦列表
			getLiveRoomVoilist()
		})
	}
	// 退出直播间
	const closeLive = () => {
		clearTimeout(VoiTime.value)
		enterRoom(false)
		offMonitor()
		return true
	}
	// 排麦列表
	const getLiveRoomVoilist = (type) => {
		if (room.value.role == 'user') startLocalAudio(false)
		liveApi.getLiveRoomVoilist({
			"liveroom.id": room.value.id
		}).then(res => {
			queueList.value = res.data
			const data = queueList.value.filter(a => a.sts == 1)
			if (data.length > 0) {
				if (room.value.role == 'anchor' || room.value.role == 'user' && data[0].member.id == user.id)
					setUserOption(data[0])

			} else {
				delUserOption()
			}
		})
	}
	// 设置连麦配置
	const anonymous = ref(true)
	const setUserOption = (e) => {
		console.log(e);
		// voists  公麦私麦
		// ano 匿名
		const {
			voists,
			ano
		} = e
		if (ano == 0) {
			// 公麦
			anonymous.value = true
		}
		if (ano == 1) {
			// 匿名
			if (room.value.role == 'anchor') {
				emit('createCustomMessage', {
					data: 'audio',
					description: `${room.value.anchor.member.id},${e.member.id}`,
					extension: ""
				})
			}

			if (room.value.role == 'user') {
				onUse({
					data: 'audio',
					description: `${room.value.anchor.member.id},${e.member.id}`,
					extension: ""
				})
			}
			anonymous.value = false
		}
		console.log(voists, ano);
		connectingId.value = e.id
		connectingUserId.value = e.member.id
		if (room.value.role == 'anchor') {
			userOption.value = {
				userId: e.member.id,
				headimg: e.member.headimg,
				nickname: e.member.nickname,
				live: true,
				audio: true
			}
		}
		// 用户才计时
		if (room.value.role == 'user') {
			params.value = {
				userId: e.member.id,
				headimg: e.member.headimg,
				nickname: e.member.nickname,
				live: true,
				audio: true
			}
			startLocalAudio(true)
			// 开启计时
		}
		if (VoiTime.value == null) memberVoiAnchorAdd()
	}
	// 退出直播间
	const delUserOption = () => {
		connectingId.value = ''
		time.value = 0
		connectingUserId.value = ''
		if (room.value.role == 'anchor') userOption.value = {
			userId: '',
			headimg: '',
			nickname: '',
			live: false,
			audio: false
		}
		if (room.value.role == 'user') params.value = {
			userId: '',
			headimg: '',
			nickname: '',
			live: false,
			audio: false
		}

		clearTimeout(VoiTime.value)
	}
	// 暂停
	const pauseNum = ref(3)
	const onPause = () => {
		if (room.value.role == 'user' && pause.value) {
			if (pauseNum.value == 0) {
				uni.showToast({
					icon: 'none',
					title: `3次暂停数已用完`
				})
				return
			} else {
				uni.showToast({
					icon: 'none',
					title: `当前剩余暂停数${pauseNum.value}`
				})
			}
			pauseNum.value -= 1
		}
		if (pauseNum.value > 0) {
			const val = {
				data: 'use',
				description: "pause",
				extension: pause.value ? '1' : "0"
			}
			if (val.description == 'pause') pause.value = !pause.value
			emit('createCustomMessage', val)
			onUse(val)
		}
	}
	// 打开排麦选项
	const openConnection = () => {
		emit('openConnection')
	}
	// 申请排麦
	const connection = (obj) => {
		const params = {
			"liveroom.id": room.value.id,
			"member.id": liveOption.value.userId,
			"anchor.id": room.value.anchor.id,
			...obj
		}
		liveApi.memberAddVoiOrder(params).then(res => {
			uni.showToast({
				icon: "none",
				title: "排麦成功"
			})
			emit('sendMsg', `${user.nickname}加入了排麦`)
			getLiveRoomVoilist()
			createCustomMessage('getLiveRoomVoilist')
		})

	}
	// 上麦
	const userConnection = (e, type) => {
		if (!type) emit('sendMsg', `${ e.member.nickname}已上麦`)
		const query = {
			id: e.id,
			"anchor.id": room.value.anchor.id
		}
		liveApi.anchorStartVoiOrder(query).then(res => {
			uni.showToast({
				icon: 'none',
				title: '上麦成功'
			})
			getLiveRoomVoilist()
			// 通知刷新排麦列表
			createCustomMessage('getLiveRoomVoilist')
		})
	}
	const VoiTime = ref(null)
	// 查询连麦时间
	const memberVoiAnchorAdd = () => {
		if (connectingId.value) {
			time.value = time.value + 1
			if (time.value % 30 === 0 && room.value.role == 'user') {
				// 30秒
				liveApi.memberVoiAnchorAdd({
					id: connectingId.value
				}).then(res => {
					if (res.data.sts == 0) {} else if (res.data.sts == 1) {
						uni.showToast({
							icon: 'none',
							title: "剩余时长不足3分钟"
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: "连麦已结束"
						})
						clearTimeout(VoiTime.value)
						VoiTime.value = null
					}
				})
			}
			VoiTime.value = setTimeout(() => {
				memberVoiAnchorAdd()
			}, 1000)
		}
	}
	// 删除排麦用户
	const delConnection = (val) => {
		console.log(val);
		if (val.sts == 0) {
			// 删除连麦
			anchorDelVoiOrder(val.id)
		}
		if (val.sts == 1) {
			// 结束连麦
			memberVoiAnchorEnd(val.id)
		}
	}
	// 主播关闭连麦
	const anchorDelVoiOrder = (id) => {
		const params = {
			id: id || connectingId.value,
			"anchor.id": room.value.anchor.id
		}
		liveApi.anchorDelVoiOrder(params).then(res => {
			getLiveRoomVoilist()
			createCustomMessage('getLiveRoomVoilist')
		})
	}
	// 主播结束连麦
	const memberVoiAnchorEnd = (id) => {
		liveApi.memberVoiAnchorEnd({
			id: id || connectingId.value
		}).then(res => {
			clearTimeout(VoiTime.value)
			time.value = 0
			getLiveRoomVoilist()
			createCustomMessage('getLiveRoomVoilist')
			startLocalAudio(false)
		})
	}
	// 进入房间
	const enterRoom = (type) => {
		if (type) {
			trtcCloud.on('onEnterRoom', (e) => {
				console.log(e);
			})
			console.log(liveOption.value);
			trtcCloud.enterRoom(liveOption.value, TRTCAppScene.TRTCAppSceneVideoCall); //进房
			if (room.value.role == 'anchor') startLocalAudio(true)
		} else {
			trtcCloud.exitRoom() //退房

		}
	}
	// 打开/关闭摄像头
	const startLocalPreview = (type) => {
		// params.value.live = !type
		// if (params.value.live) {
		// 	trtcCloud.startLocalPreview(true, liveOption.value.userId); //摄像头
		// } else {
		// 	trtcCloud.stopLocalPreview() //摄像头
		// }
	}


	// 通知直播间更新排麦列表
	const createCustomMessage = (type, val) => {
		emit('createCustomMessage', {
			data: 'use',
			description: type,
			extension: val || ""
		})
	}
	// 接受操作
	const onUse = (val) => {
		if (val.data == 'audio') {
			// 连麦权限
			if (val.description.indexOf(user.value.id) == -1) {
				// 
				console.log('静音');
				trtcCloud.muteAllRemoteAudio(false) //非静音掉所有用户的声音
			} else {
				console.log('不静音');
				trtcCloud.muteAllRemoteAudio(true) //非静音掉所有用户的声音
			}
		}
		// 刷新排麦列表
		if (val.description == 'getLiveRoomVoilist') getLiveRoomVoilist()
		// 暂停
		if (val.description == 'pause') {
			if (val.extension == '0') {
				// 恢复
				pause.value = true
				console.log('恢复');
				memberVoiAnchorAdd()
				trtcCloud.muteAllRemoteAudio(false) //非静音掉所有用户的声音
			} else {
				// 暂停
				console.log('暂停');
				pause.value = false
				trtcCloud.muteAllRemoteAudio(true) //非静音掉所有用户的声音
				clearTimeout(VoiTime.value)
				VoiTime.value = null
			}
		}
		// 下麦
		if (val.description == 'break') {
			clearTimeout(VoiTime.value)
			connectingUserId.value = ""
			getLiveRoomVoilist()
			startLocalAudio(false)
			nextTick(() => {
				params.value.userId = ''
			})
		}
	}
	// 进入房间
	const onRemoteUserEnterRoom = (userId) => {
		console.log('进入room', userId);
		emit('createCustomMessage', {
			data: 'roomHot',
			description: userId,
			extension: `add`
		})
		// 添加主播视频
		// if (room.value.role === 'user' && userOption.value.userId == '') userOption.value.userId = userId
		// else userOption.value.userId = userId
	}
	// 退出房间
	const onRemoteUserLeaveRoom = (res) => {
		console.log('退出room', res);
		emit('createCustomMessage', {
			data: 'roomHot',
			description: userId,
			extension: `add`
		})
		liveApi.memberLeaveliveRoom({
			"member.id": res.userId,
			"liveroom.id": room.value.id
		})
		if (res.userId === room.value.anchor.member.id) {
			trtcCloud.muteAllRemoteAudio(true)
			uni.navigateBack({
				delta: 1
			})
		}
		// if (room.value.role == 'anchor') emit('createCustomMessage', {
		// 	data: 'roomHot',
		// 	description: res.userId,
		// 	extension: `del`
		// })
		// const {
		// 	userId,
		// 	reason
		// } = res
		// if (userId === userOption.value.userId) userOption.value.userId = ""
		// tips.value.push(`${userId}${reason!==0?reason!==1?'踢出房间':'超时退出':'退出房间'}`)
	}
	// 查询用户信息
	const queryMemberInfo = (id) => {
		return userApi.queryMemberInfo({
			id: id
		})
	}

	// 视频
	const onUserVideoAvailable = (res) => {
		// const {
		// 	userId,
		// 	available
		// } = res;
		// // console.log('live', res);
		// userOption.value.live = available
		// nextTick(() => {
		// 	if (userId && available) {
		// 		trtcCloud.startRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSmall,
		// 			userId);
		// 		// tips.value.push(`${userId}开启视频`)
		// 	} else {
		// 		trtcCloud.stopRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSmall);
		// 		// tips.value.push(`${userId}关闭视频`)
		// 	}
		// })
	}
	// 打开/关闭麦克风
	const startLocalAudio = (type) => {
		params.value.audio = type
		if (type) {
			trtcCloud.startLocalAudio(); //麦克风
		} else {
			trtcCloud.stopLocalAudio(); //麦克风
		}
	}
	// 音频
	const onUserAudioAvailable = async (res) => {
		console.log('audio', res);
		const {
			userId,
			available
		} = res;
		trtcCloud.muteRemoteAudio(userId, false)
		// if (userId != userOption.value.userId) {
		// 	if (room.value.role != 'user') params.value.audio = available
		// 	else userOption.value.audio = available
		// }
		// trtcCloud.muteRemoteAudio(userId, false);
		// if (userId && available) {
		// console.log(connectingUserId.value);
		// tips.value.push(`${userId}开启声音`)
		// if (room.value.role == 'user') {
		// 	const val = await queryMemberInfo(userId)
		// 	userOption.value.userId = userId
		// 	userOption.value.audio = true
		// 	userOption.value.headimg = val.data.member.headimg
		// 	userOption.value.nickname = val.data.member.nickname
		// }

		// } else {
		// trtcCloud.muteRemoteAudio(userId, true)
		// 当远端用户关闭视频流时，停止订阅
		// tips.value.push(`${userId}关闭声音`)
		// }
		// userOption.value.audio = available
	}
	// 监听
	const onMonitor = () => {
		// 监听房间人员进入
		trtcCloud.on("onRemoteUserEnterRoom", onRemoteUserEnterRoom);
		// 监听房间人员离开
		trtcCloud.on("onRemoteUserLeaveRoom", onRemoteUserLeaveRoom);
		// // 监听房间其他人的视频
		// trtcCloud.on('onUserVideoAvailable', onUserVideoAvailable);
		// 监听房间其他人的音频
		// trtcCloud.on('onUserAudioAvailable', onUserAudioAvailable);
	}
	// 退出监听
	const offMonitor = () => {
		if (trtcCloud) {
			// 监听房间人员进入
			trtcCloud.off("onRemoteUserEnterRoom", onRemoteUserEnterRoom);
			// 监听房间人员离开
			trtcCloud.off("onRemoteUserLeaveRoom", onRemoteUserLeaveRoom);
			// // 监听房间其他人的视频
			// trtcCloud.off('onUserVideoAvailable', onUserVideoAvailable);
			// 监听房间其他人的音频
			// trtcCloud.off('onUserAudioAvailable', onUserAudioAvailable);
		}
	}
	defineExpose({
		startLive,
		closeLive,
		onUse,
		popupRef,
		onPause,
		startLocalAudio,
		connection
	})
</script>

<style>
</style>